<!DOCTYPE html>












  


<html class="theme-next mist use-motion" lang="en">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2">
<meta name="theme-color" content="#222">






  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.3.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/imagesfavicon.ico?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/imagesfavicon.ico?v=6.3.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '6.3.0',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>
  <meta name="description" content="前言—–冯延巳： 鹊踏枝.清明  六曲阑干偎碧树，杨柳风轻，展尽黄金缕。谁把钿筝移玉柱？穿帘海燕惊飞去。满眼游丝兼落絮，红杏开时，一霎清明雨。浓睡觉来慵不语，惊残好梦无寻处？   小假前夕，大Boss让当差，于是便可以名正言顺的重温一下数据库；时间还真是一把XXXX，夺走了记忆，失掉了“手熟尔”。  说明1: 内容：sql语句相关：建表、查询、权限等；2: 环境：Ubuntu 14.04 LTS下">
<meta name="keywords" content="Mysql,Database">
<meta property="og:type" content="article">
<meta property="og:title" content="数据库题目整理及详解（一）">
<meta property="og:url" content="https://absentm.github.io/2016/04/02/数据库题目整理及详解（一）/index.html">
<meta property="og:site_name" content="AbsentM&#39;s Notes">
<meta property="og:description" content="前言—–冯延巳： 鹊踏枝.清明  六曲阑干偎碧树，杨柳风轻，展尽黄金缕。谁把钿筝移玉柱？穿帘海燕惊飞去。满眼游丝兼落絮，红杏开时，一霎清明雨。浓睡觉来慵不语，惊残好梦无寻处？   小假前夕，大Boss让当差，于是便可以名正言顺的重温一下数据库；时间还真是一把XXXX，夺走了记忆，失掉了“手熟尔”。  说明1: 内容：sql语句相关：建表、查询、权限等；2: 环境：Ubuntu 14.04 LTS下">
<meta property="og:locale" content="en">
<meta property="og:image" content="http://img.blog.csdn.net/20160402114446890">
<meta property="og:image" content="http://img.blog.csdn.net/20160402114355124">
<meta property="og:image" content="http://img.blog.csdn.net/20160402114610546">
<meta property="og:image" content="http://img.blog.csdn.net/20160402115121830">
<meta property="og:image" content="http://img.blog.csdn.net/20160402115240908">
<meta property="og:image" content="http://img.blog.csdn.net/20160402115256424">
<meta property="og:image" content="http://img.blog.csdn.net/20160402115503581">
<meta property="og:image" content="http://img.blog.csdn.net/20160402115807317">
<meta property="og:image" content="http://img.blog.csdn.net/20160402115948333">
<meta property="og:image" content="http://img.blog.csdn.net/20160402120043599">
<meta property="og:updated_time" content="2017-11-21T11:44:44.755Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="数据库题目整理及详解（一）">
<meta name="twitter:description" content="前言—–冯延巳： 鹊踏枝.清明  六曲阑干偎碧树，杨柳风轻，展尽黄金缕。谁把钿筝移玉柱？穿帘海燕惊飞去。满眼游丝兼落絮，红杏开时，一霎清明雨。浓睡觉来慵不语，惊残好梦无寻处？   小假前夕，大Boss让当差，于是便可以名正言顺的重温一下数据库；时间还真是一把XXXX，夺走了记忆，失掉了“手熟尔”。  说明1: 内容：sql语句相关：建表、查询、权限等；2: 环境：Ubuntu 14.04 LTS下">
<meta name="twitter:image" content="http://img.blog.csdn.net/20160402114446890">






  <link rel="canonical" href="https://absentm.github.io/2016/04/02/数据库题目整理及详解（一）/">



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>数据库题目整理及详解（一） | AbsentM's Notes</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?021d64369b3c401c47c6ab7aa56f7074";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">AbsentM's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="Toggle navigation bar">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br>Home</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br>Categories</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>Archives</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>Tags</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br>About</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>Search</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  
    <div class="reading-progress-bar"></div>
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://absentm.github.io/2016/04/02/数据库题目整理及详解（一）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="AbsentM">
      <meta itemprop="description" content="Avenue to Jane!">
      <meta itemprop="image" content="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/googlrPhoto.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="AbsentM's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">数据库题目整理及详解（一）
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              

              
                
              

              <time title="Created: 2016-04-02 12:05:01" itemprop="dateCreated datePublished" datetime="2016-04-02T12:05:01+08:00">2016-04-02</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Edited on</span>
                
                <time title="Modified: 2017-11-21 19:44:44" itemprop="dateModified" datetime="2017-11-21T19:44:44+08:00">2017-11-21</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Database-Notes/" itemprop="url" rel="index"><span itemprop="name">Database Notes</span></a></span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2016/04/02/数据库题目整理及详解（一）/#comments" itemprop="discussionUrl">
                
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2016/04/02/数据库题目整理及详解（一）/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2016/04/02/数据库题目整理及详解（一）/" class="leancloud_visitors" data-flag-title="数据库题目整理及详解（一）">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">Views: </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>—–冯延巳： 鹊踏枝.清明</p>
<blockquote>
<p>六曲阑干偎碧树，杨柳风轻，展尽黄金缕。谁把钿筝移玉柱？穿帘海燕惊飞去。<br>满眼游丝兼落絮，红杏开时，一霎清明雨。浓睡觉来慵不语，惊残好梦无寻处？ </p>
</blockquote>
<p>小假前夕，大Boss让当差，于是便可以名正言顺的重温一下数据库；时间还真是一把XXXX，夺走了记忆，失掉了“手熟尔”。</p>
<hr>
<h2 id="说明"><a href="#说明" class="headerlink" title="说明"></a>说明</h2><p>1: 内容：sql语句相关：建表、查询、权限等；<br>2: 环境：Ubuntu 14.04 LTS下的Mysql5.5，详见下配图：</p>
<p> <img src="http://img.blog.csdn.net/20160402114446890" alt="mysql version"><br>3: 环境搭建见：<a href="http://jingyan.baidu.com/article/425e69e6bbc6c7be14fc1640.html" target="_blank" rel="noopener">ubuntu下mysql数据库的安装配置</a><br>4: 规范：解析中的<strong>SQL关键字</strong>都使用黑粗体标记了，并且有大小写的区分；Mysql中是对sql语句大小写敏感的，为了节省时间，在亲测中都使用小写，详见截图;<br>5: 每书写一条sql语句，最后都需要加英文分号（“;”）;<br>6: 每一行sql语句基本都亲测了一下，望诸君戮力，多有指正。</p>
<hr>
<h2 id="题目解析"><a href="#题目解析" class="headerlink" title="题目解析"></a>题目解析</h2><p>1: 设供应商-工程-零件数据库包含如下关系:</p>
<blockquote>
<p>Suppliers(Sno, Sname, Status, Scity)<br>Parts(Pno, Pname, Color, Weight)<br>Projects(Jno, Jname, Jcity)<br>SPJ(Sno, Pno, Jno, Quantity)</p>
</blockquote>
<p>其中,各关系的主码用下横线标示。Sno, Sname, Status, Scity 分别表示供应商的编号、名称、状态和所在城市;Pno, Pname, Color, Weight 分别表示零件的编号、名称、颜色和重量;Jno, Jname, Jcity 分别表示工程的编号、名称和所在城市; SPJ 是供应关系,Quantity 是特定供应商一次向特定工程供应的特定零件的数量。请使用 SQL 语句表示如下功能:</p>
<blockquote>
<p>题目都比较简单，开始之前，做部分初始化：</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">create database stu;         ## 创建名为：stu的数据库</span><br><span class="line">use stu;                     ## 使用stu数据库</span><br></pre></td></tr></table></figure>
<p>(1) 使用 SQL 创建基本表,确定每个属性的类型、缺省值和约束条件。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE Suppliers (</span><br><span class="line">Sno CHAR (8) PRIMARY KEY,</span><br><span class="line">Sname CHAR (8) NOT NULL,</span><br><span class="line">Status INT,</span><br><span class="line">Scity CHAR(10));</span><br></pre></td></tr></table></figure>
<p>同时<code>insert into ... values()</code> 语句添加部分测试数据，见下图（之后皆同）：</p>
<p><img src="http://img.blog.csdn.net/20160402114355124" alt="suppliers"></p>
<hr>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE Parts (</span><br><span class="line">Pno CHAR (8) PRIMARY KEY,</span><br><span class="line">Pname CHAR(16) NOT NULL,</span><br><span class="line">Color CHAR(4),</span><br><span class="line">Weight NUMERIC(7, 2));</span><br></pre></td></tr></table></figure>
<p>见下图：</p>
<p><img src="http://img.blog.csdn.net/20160402114610546" alt="parts"></p>
<hr>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE Projects (</span><br><span class="line">Jno CHAR (8) PRIMARY KEY,</span><br><span class="line">Jname CHAR(20) NOT NULL,</span><br><span class="line">Jcity CHAR(10));</span><br></pre></td></tr></table></figure>
<p>注意, 该处在操作时，将表名写为：project了，于是使用 alter语句修改表名：<code>alter table project rename to projects;</code></p>
<p>见下图：</p>
<p><img src="http://img.blog.csdn.net/20160402115121830" alt="projects"></p>
<hr>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE SPJ (</span><br><span class="line">Sno CHAR (8),</span><br><span class="line">Pno CHAR(8),</span><br><span class="line">Jno CHAR(8),</span><br><span class="line">Quantity INT,</span><br><span class="line">PRIMARY KEY (Sno,Pno,Jno),</span><br><span class="line">FOREIGN KEY (Sno) REFERENCES Suppliers(Sno),</span><br><span class="line">FOREIGN KEY (Pno) REFERENCES Parts(Pno),</span><br><span class="line">FOREIGN KEY (Jno) REFERENCES Projects(Jno) );</span><br></pre></td></tr></table></figure>
<p>该处使用了外键，注意单词一定不要拼错，在测试中 <code>PRIMARY KEY、FOREIGN KEY</code>的内容都需要使用括号括起来，不然会报语法错误的提示，详见下图；</p>
<p><img src="http://img.blog.csdn.net/20160402115240908" alt="spj"></p>
<p><img src="http://img.blog.csdn.net/20160402115256424" alt="spj_insert"></p>
<hr>
<p>(2) 求上海的所有供应商的信息。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT * FROM Suppliers WHERE Scity=‘上海’;</span><br></pre></td></tr></table></figure>
<p>(3) 求位于北京的所有工程的信息。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT * FROM Projects WHERE Jcity=‘北京’;</span><br></pre></td></tr></table></figure>
<p>(4) 求数量在 100-150 的供应。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT * FROM SPJ WHERE Quantity BETWEEN 100 AND 150;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意此处: 使用<code>between ... and</code> 语句。</p>
</blockquote>
<p>(5) 求为工程 J1 提供零件的供应商号。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT Sno FROM SPJ WHERE Jno=‘J1’;</span><br></pre></td></tr></table></figure>
<p>(6) 求供应工程 J1 红色零件的供应商号。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT Sno</span><br><span class="line">FROM SPJ, Parts</span><br><span class="line">WHERE SPJ.Pno=Parts.Pno AND Jno=‘J1’ AND Color=‘红色’;</span><br></pre></td></tr></table></figure>
<p>(7) 求至少提供一种红色零件的供应商名称。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT Sname</span><br><span class="line">FROM SPJ, Parts, Suppliers</span><br><span class="line">WHERE SPJ.Pno=Parts.Pno AND SPJ.Sno=Suppliers.Sno AND Color=‘红色’;</span><br></pre></td></tr></table></figure>
<p>2 ~ 7 题亲测截图：</p>
<p><img src="http://img.blog.csdn.net/20160402115503581" alt="2-7"></p>
<p>(8) 求不提供零件 P2 的供应商名称。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">SELECT Sname</span><br><span class="line">FROM Suppliers</span><br><span class="line">WHERE NOT EXISTS</span><br><span class="line">	(SELECT *</span><br><span class="line">	FROM SPJ</span><br><span class="line">	WHERE SPJ.Sno= Suppliers.Sno AND Pno=‘P2’);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意此处: 使用<code>not exists</code> 语句。</p>
</blockquote>
<p>(9) 求没有使用天津供应商生产的红色零件的工程号。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">SELECT Jno</span><br><span class="line">FROM Projects</span><br><span class="line">WHERE NOT EXISTS</span><br><span class="line">	(SELECT *</span><br><span class="line">	 FROM SPJ, Parts, SuppliersWHERE SPJ.Sno= Suppliers.Sno AND</span><br><span class="line">	 Parts.Pno=SPJ.Pno AND</span><br><span class="line">	 Color=‘红色’ AND Scity=‘天津’);</span><br></pre></td></tr></table></figure>
<p>(10) 求使用了本地供应商提供的零件的工程号。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">SELECT Projects.Jno, Projects.Jname</span><br><span class="line">FROM Projects,Suppliers,SPJ</span><br><span class="line">WHERE SPJ.Sno= Suppliers.Sno AND</span><br><span class="line">	Projects.Jno=SPJ.Jno AND</span><br><span class="line">	Projects.Jcity= Suppliers.Scity;</span><br></pre></td></tr></table></figure>
<p>或</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">SELECT Jno,Jname</span><br><span class="line">FROM Projects</span><br><span class="line">WHERE EXISTS (</span><br><span class="line">	SELECT *</span><br><span class="line">	FROM SPJ, Suppliers</span><br><span class="line">	WHERE SPJ.Sno= Suppliers.Sno AND</span><br><span class="line">		Projects.Jno=SPJ.Jno AND</span><br><span class="line">		Projects.Jcity= Suppliers.Scity);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意此处: 使用<code>exists</code> 语句。</p>
</blockquote>
<p>8 ~ 10，亲测截图：</p>
<p><img src="http://img.blog.csdn.net/20160402115807317" alt="8-10"></p>
<p>(11)  求未使用本地供应商提供的零件的工程号和工程名称。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">SELECT Jno,Jname</span><br><span class="line">FROM Projects</span><br><span class="line">WHERE NOT EXISTS (</span><br><span class="line">	SELECT *</span><br><span class="line">	FROM SPJ, Suppliers</span><br><span class="line">	WHERE SPJ.Sno= Suppliers.Sno AND</span><br><span class="line">            Projects.Jno=SPJ.Jno AND</span><br><span class="line">            Projects.Jcity= Suppliers.Scity);</span><br></pre></td></tr></table></figure>
<p>(12) 求至少用了供应商 S1 所供应的全部零件的工程号。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">SELECT Jno</span><br><span class="line">FROM Projects</span><br><span class="line">WHERE NOT EXISTS (</span><br><span class="line">	SELECT *</span><br><span class="line">	FROM SPJ SPJ1</span><br><span class="line">	WHERE SPJ1.Sno = ‘S1’ AND</span><br><span class="line">	NOT EXISTS (</span><br><span class="line">		SELECT *</span><br><span class="line">		FROM SPJ SPJ2</span><br><span class="line">		WHERE SPJ2.Jno= Projects.Jno AND</span><br><span class="line">		SPJ2.Pno= SPJ1.Pno));</span><br></pre></td></tr></table></figure>
<p>(13) 求提供所有零件的供应商名称。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">SELECT Sname</span><br><span class="line">FROM Suppliers</span><br><span class="line">WHERE NOT EXISTS (</span><br><span class="line">	SELECT *</span><br><span class="line">	FROM SPJ SPJ1</span><br><span class="line">		WHERE NOT EXISTS (</span><br><span class="line">			SELECT *</span><br><span class="line">            FROM SPJ SPJ2</span><br><span class="line">            WHERE SPJ2.Sno= Suppliers.Sno AND</span><br><span class="line">            SPJ2.Pno= SPJ1.Pno));</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意此处: 使用建立<strong>别名</strong>的机制。</p>
</blockquote>
<p>(14) 求提供了零件的供应商的个数。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT distinct Sno FROM SPJ;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意此处的<code>distinct</code>语句。    </p>
</blockquote>
<p>11 ～ 14，截图：</p>
<p><img src="http://img.blog.csdn.net/20160402115948333" alt="11-14"></p>
<p>(15) 求所有零件的平均重量。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT avg(weight) FROM Parts;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意此处的<code>avg</code>函数，用于求取平均值。    </p>
</blockquote>
<p>(16) 求供应商 S1 提供的每种零件的总数量。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT Pno, sum(quantity) FROM SPJ WHERE Sno=‘S1’ GROUP BY Pno;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意此处的<code>sum</code>函数，用于求和；以及<code>GROUP BY</code>语句用于分组。    </p>
</blockquote>
<p>(17) 求供应商 S1 供应工程 J1 的每种零件的总重量。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">SELECT sum(weight)</span><br><span class="line">FROM Parts, SPJ</span><br><span class="line">WHERE SPJ.Pno=Parts.Pno AND Sno=‘S1’ AND Jno=‘J1’</span><br><span class="line">GROUP BY Parts.Pno;</span><br></pre></td></tr></table></figure>
<p>15 ~ 17，亲测截图：</p>
<p><img src="http://img.blog.csdn.net/20160402120043599" alt="15-17"></p>
<hr>
<p>@@@@@@@<strong>看来这部分要写成系列的了，今天就到这儿，未完待续……</strong></p>
<h2 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h2><p>[1]. <a href="http://www.shuojuzi.com/s/shicidaquan/128764.html" target="_blank" rel="noopener">http://www.shuojuzi.com/s/shicidaquan/128764.html</a><br>[2]. <a href="https://www.douban.com/note/155415235/" target="_blank" rel="noopener">https://www.douban.com/note/155415235/</a><br>[3]. <a href="http://www.cnblogs.com/wzmenjoy/p/4244545.html" target="_blank" rel="noopener">http://www.cnblogs.com/wzmenjoy/p/4244545.html</a><br>[4]. <a href="http://www.tanbo.name/html/544.html" target="_blank" rel="noopener">http://www.tanbo.name/html/544.html</a><br>[5]. <a href="http://jxtm.jzu.cn/?p=258" target="_blank" rel="noopener">http://jxtm.jzu.cn/?p=258</a><br>[6]. <a href="http://www.jb51.net/article/23966.htm" target="_blank" rel="noopener">http://www.jb51.net/article/23966.htm</a><br>[7]. <a href="http://jingyan.baidu.com/article/425e69e6bbc6c7be14fc1640.html" target="_blank" rel="noopener">http://jingyan.baidu.com/article/425e69e6bbc6c7be14fc1640.html</a></p>
      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center">
  <div>Enjoy it ? Donate me !  求鼓励，求支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>Donate</span>
  </button>
  <div id="QR" style="display: none">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/wechat.png" alt="AbsentM WeChat Pay">
        <p>WeChat Pay</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/alipay.png" alt="AbsentM Alipay">
        <p>Alipay</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Mysql/" rel="tag"># Mysql</a>
          
            <a href="/tags/Database/" rel="tag"># Database</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/03/28/使用U盘安装windows系统教程/" rel="next" title="使用优盘安装 Windows 系统教程">
                <i class="fa fa-chevron-left"></i> 使用优盘安装 Windows 系统教程
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/04/03/数据库题目整理及详解（二）/" rel="prev" title="数据库题目整理及详解（二）">
                数据库题目整理及详解（二） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/googlrPhoto.png" alt="AbsentM">
            
              <p class="site-author-name" itemprop="name">AbsentM</p>
              <p class="site-description motion-element" itemprop="description">Avenue to Jane!</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">57</span>
                    <span class="site-state-item-name">posts</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">8</span>
                    <span class="site-state-item-name">categories</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">37</span>
                    <span class="site-state-item-name">tags</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/absentm" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://twitter.com/absentm123" target="_blank" title="Twitter"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://weibo.com/dmicrocosmos" target="_blank" title="Weibo"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  
                </span>
              
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.hanhanfilm.com/" title="憨憨电影" target="_blank">憨憨电影</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.fengxiaochuang.com/" title="晓闯博客" target="_blank">晓闯博客</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#说明"><span class="nav-number">2.</span> <span class="nav-text">说明</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#题目解析"><span class="nav-number">3.</span> <span class="nav-text">题目解析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考资料"><span class="nav-number">4.</span> <span class="nav-text">参考资料</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">AbsentM</span>

  

  
</div>




  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme – <a class="theme-link" target="_blank" href="https://theme-next.org">NexT.Mist</a> v6.3.0</div>
        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="Total Visitors">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="Total Views">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
	
    

    
      <div>
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-58d66725c4aec37d" async="async"></script>
</div>

      </div>
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























  



  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/reading_progress/reading_progress.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.3.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.3.0"></script>



  

  
    <script id="dsq-count-scr" src="https://absentm.disqus.com/count.js" async></script>
  

  
    <script type="text/javascript">
      var disqus_config = function () {
        this.page.url = 'https://absentm.github.io/2016/04/02/数据库题目整理及详解（一）/';
        this.page.identifier = '2016/04/02/数据库题目整理及详解（一）/';
        this.page.title = '数据库题目整理及详解（一）';
        };
      function loadComments () {
        var d = document, s = d.createElement('script');
        s.src = 'https://absentm.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      }
      
        $(function () {
          var offsetTop = $('#comments').offset().top - $(window).height();
          if (offsetTop <= 0) {
            // load directly when there's no a scrollbar
            loadComments();
          } else {
            $(window).on('scroll.disqus_scroll', function () {
              var scrollTop = document.documentElement.scrollTop;
              if (scrollTop >= offsetTop) {
                $(window).off('.disqus_scroll');
                loadComments();
              }
            });
          }
        });
      
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("8gIMbJWMH7XprqgkEiPWXvuu-gzGzoHsz", "W9NRpyhllWph45XiJsEHVgct");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            
            counter.save(null, {
              success: function(counter) {
                
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(counter.get('time'));
                
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            
              var newcounter = new Counter();
              /* Set ACL */
              var acl = new AV.ACL();
              acl.setPublicReadAccess(true);
              acl.setPublicWriteAccess(true);
              newcounter.setACL(acl);
              /* End Set ACL */
              newcounter.set("title", title);
              newcounter.set("url", url);
              newcounter.set("time", 1);
              newcounter.save(null, {
                success: function(newcounter) {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
                },
                error: function(newcounter, error) {
                  console.log('Failed to create');
                }
              });
            
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  

  


  
  

  

  

  

  

  

</body>
</html>